package thesis.bean;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.HttpSession;

import thesis.database.User;
import thesis.javaclass.SystemModel;

@ManagedBean(name = "user")
@SessionScoped
public class UserBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String userName, password, message;
	User userAcc;
	boolean loggedIn;
	ArrayList<User> users;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User getUserAcc() {
		return userAcc;
	}

	public String getMessage() {
		return message;
	}

	public String logIn() {
		this.userAcc = SystemModel.validate(userName, password);
		if (userAcc == null) {
			message = "Invalid username or password!";
			loggedIn = false;

			return ("login?faces-redirect=true");
		} else if (userAcc.isActive() == false) {
			message = "This account hasn't actived yet!";
			loggedIn = false;

			return ("login?faces-redirect=true");
		} else {
			message = "";
			loggedIn = true;

			userAcc.setLastLoginTime(new Timestamp(new Date().getTime()));
			SystemModel.updateUser(userAcc);

			return ("service?faces-redirect=true");
		}

	}

	public String logOut() {
		if (userAcc != null) {
			FacesContext.getCurrentInstance().getExternalContext()
					.invalidateSession();
		}

		loggedIn = false;
		return ("login?faces-redirect=true");
	}

}
